﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using NET4.DataNET4;
using NET4.DataNET4.Repository;
using System.Net.Mail;
using NET4.Database;
using System.Web;
using System.Net;
using System.Configuration;
using System.IO;

namespace NET4.Programma
{
  public partial class SendOfferRequest : Form
  {
    #region Delegates & Events
    public delegate void OfferRequestSendHandling(object sender, OfferRequestSendEventArgs e);
    public event OfferRequestSendHandling OfferRequestSend;
    #endregion

    #region Properties
    private OfferteAanvraag offerRequest;
    public OfferteAanvraag OfferRequest
    {
      get { return this.offerRequest; }
      set { this.offerRequest = value; }
    }

    private List<Leverancier> suppliers;
    protected List<Leverancier> Suppliers
    {
      get
      {
        if (this.suppliers == null) { this.suppliers = new List<Leverancier>(); }
        return this.suppliers;
      }
      set
      {
        this.suppliers = value;
      }
    }

    private List<Leverancier> selectedSuppliers;
    protected List<Leverancier> SelectedSuppliers
    {
      get
      {
        if (this.selectedSuppliers == null) { this.selectedSuppliers = new List<Leverancier>(); }
        return this.selectedSuppliers;
      }
      set
      {
        this.selectedSuppliers = value;
      }
    }

    private List<Leverancier> receiverSuppliers;
    protected List<Leverancier> ReceiverSuppliers
    {
      get
      {
        if (this.receiverSuppliers == null) { this.receiverSuppliers = new List<Leverancier>(); }
        return this.receiverSuppliers;
      }
      set
      {
        this.receiverSuppliers = value;
      }
    }

    private List<Leverancier> selectedReceiverSuppliers;
    public List<Leverancier> SelectedReceiverSuppliers
    {
      get
      {
        if (this.selectedReceiverSuppliers == null) { this.selectedReceiverSuppliers = new List<Leverancier>(); }
        return this.selectedReceiverSuppliers;
      }
      set
      {
        this.selectedReceiverSuppliers = value;
      }
    }
    #endregion

    public SendOfferRequest()
    {
      InitializeComponent();
    }

    #region Protected methods
    protected void OnOfferRequestSend()
    {
      if (this.OfferRequestSend != null)
      {
        this.OfferRequestSend(this, new OfferRequestSendEventArgs(this.OfferRequest));
      }
    }

    protected void Init()
    {
      this.txtQuantity.Text = this.OfferRequest.Aantal.ToString();
      this.txtDescription.Text = this.OfferRequest.Omschrijving;

      if (this.OfferRequest.Afbeelding != null)
      {
        MemoryStream ms = new MemoryStream(this.OfferRequest.Afbeelding.ToArray());
        this.pbImage.Image = Image.FromStream(ms);
      }

      this.Suppliers = LeverancierRepository.Instance.List();

      List<Leverancier> selectedSuppliers = new List<Leverancier>();
      if (this.Suppliers.Count > 0)
      {
        selectedSuppliers.Add(this.Suppliers.First());
      }

      this.RefreshGrids(selectedSuppliers, new List<Leverancier>());
    }

    protected void RefreshGrids(List<Leverancier> selectedSuppliers, List<Leverancier> selectedReceiverSuppliers)
    {
      this.dgvSuppliers.DataSource = null;
      this.dgvReceiverSuppliers.DataSource = null;

      this.SelectedSuppliers = selectedSuppliers;
      
      this.dgvSuppliers.AutoGenerateColumns = false;
      this.dgvSuppliers.DataSource = this.Suppliers;

      foreach (DataGridViewRow row in this.dgvSuppliers.Rows)
      {
        Int32 id = 0;
        Int32.TryParse(row.Cells[0].Value.ToString(), out id);

        row.Selected = this.SelectedSuppliers.Exists(delegate(Leverancier l) { return l.Id == id; });
      }

      this.InitSupplierButtons();

      this.SelectedReceiverSuppliers = selectedReceiverSuppliers;

      this.dgvReceiverSuppliers.AutoGenerateColumns = false;
      this.dgvReceiverSuppliers.DataSource = this.ReceiverSuppliers;

      foreach (DataGridViewRow row in this.dgvReceiverSuppliers.Rows)
      {
        Int32 id = 0;
        Int32.TryParse(row.Cells[0].Value.ToString(), out id);

        row.Selected = this.SelectedReceiverSuppliers.Exists(delegate(Leverancier l) { return l.Id == id; });
      }

      this.InitReceiverSupplierButtons();

      this.btnSend.Enabled = (this.ReceiverSuppliers.Count > 0);
    }

    protected void InitSupplierButtons()
    {
      this.btnAddAllSuppliers2Receiver.Enabled = (this.SelectedSuppliers.Count > 0);
      this.btnAddSupplierToReceiver.Enabled = (this.SelectedSuppliers.Count > 0);
    }

    protected void InitReceiverSupplierButtons()
    {
      this.btnRemoveSupplier2Receiver.Enabled = (this.SelectedReceiverSuppliers.Count > 0);
      this.btnRemoveAllSuppliers2Receiver.Enabled = (this.SelectedReceiverSuppliers.Count > 0);
    }

    protected Boolean Send()
    {
      Boolean result = true;

      try
      {
        String from = "no-reply@windesheim.nl";
        String subject = "Offerte aanvraag";

        String smtpAddress = ConfigurationManager.AppSettings["SmtpAddress"].ToString();
        Int32 smtpPort = 0;
        Int32.TryParse(ConfigurationManager.AppSettings["SmtpPort"].ToString(), out smtpPort);
        String smtpUser = ConfigurationManager.AppSettings["SmtpUser"];
        String smtpPassword = ConfigurationManager.AppSettings["SmtpPassword"];

        if (smtpPassword != String.Empty)
        {
          smtpPassword = AES.Decrypt(HttpUtility.UrlDecode(smtpPassword), "net4");
        }

        SmtpClient smtpClient;
        if (smtpPort != 0)
        {
          smtpClient = new SmtpClient(smtpAddress, smtpPort);
          smtpClient.Credentials = new NetworkCredential(smtpUser, smtpPassword);
        }
        else
        {
          smtpClient = new SmtpClient(smtpAddress);
        }

        foreach (Leverancier supplier in this.ReceiverSuppliers)
        {
          Offerte offer = new Offerte();
          offer.LeverancierId = supplier.Id;
          offer.OfferteAanvraagId = this.OfferRequest.Id;
          OfferteRepository.Instance.Save(offer);

          String url = String.Format("{0}/?id={1}", "http://localhost/Website", HttpUtility.UrlEncode(AES.Encrypt(offer.OfferteId.ToString(), "net4")));
          String body = String.Empty;

          body = String.Concat(body, "<font style=\"font-family:Arial;font-size:12px;\"><p>Er is zojuist een offerte aanvraag gedaan. U kunt uw offerte invullen via de onderstaande link.</p>");
          body = String.Concat(body, String.Format("<a href=\"{0}\">{0}</a></font>", url));

          MailMessage mailMessage = new MailMessage(new MailAddress(from, "Windesheim"), new MailAddress(supplier.Email));
          mailMessage.Subject = subject;
          mailMessage.Body = body;
          mailMessage.IsBodyHtml = true;

          smtpClient.Send(mailMessage);
        }
      }
      catch (Exception)
      {
        result = false;
      }

      return result;
    }
    #endregion

    #region EventHandlers
    private void SendOfferRequest_Load(object sender, EventArgs e)
    {
      this.Init();
    }

    private void dgvSuppliers_CellClick(object sender, DataGridViewCellEventArgs e)
    {
      this.SelectedSuppliers = new List<Leverancier>();

      foreach (DataGridViewRow selectedRow in this.dgvSuppliers.SelectedRows)
      {
        Int32 id = 0;
        Int32.TryParse(selectedRow.Cells[0].Value.ToString(), out id);

        Leverancier supplier = LeverancierRepository.Instance.Select(id);

        if (supplier != null)
        {
          this.SelectedSuppliers.Add(supplier);
        }
      }
    }

    private void dgvReceiverSuppliers_CellClick(object sender, DataGridViewCellEventArgs e)
    {
      this.SelectedReceiverSuppliers = new List<Leverancier>();

      foreach (DataGridViewRow selectedRow in this.dgvReceiverSuppliers.SelectedRows)
      {
        Int32 id = 0;
        Int32.TryParse(selectedRow.Cells[0].Value.ToString(), out id);

        Leverancier supplier = LeverancierRepository.Instance.Select(id);

        if (supplier != null)
        {
          this.SelectedReceiverSuppliers.Add(supplier);
        }
      }
    }
    
    private void btnAddAllSuppliers2Receiver_Click(object sender, EventArgs e)
    {
      List<Leverancier> selectedRecieverSuppliers = this.Suppliers;

      this.ReceiverSuppliers.AddRange(this.Suppliers);
      this.Suppliers = new List<Leverancier>();

      this.RefreshGrids(new List<Leverancier>(), selectedRecieverSuppliers);
    }

    private void btnAddSupplierToReceiver_Click(object sender, EventArgs e)
    {
      this.ReceiverSuppliers.AddRange(this.SelectedSuppliers);

      foreach (Leverancier supplier in this.SelectedSuppliers)
      {
        this.Suppliers.Remove(supplier);
      }

      List<Leverancier> selectedSupplier = new List<Leverancier>();
      if (this.Suppliers.Count > 0)
      {
        selectedSupplier.Add(this.Suppliers.First());
      }

      this.RefreshGrids(selectedSupplier, this.SelectedSuppliers);
    }

    private void btnRemoveSupplier2Receiver_Click(object sender, EventArgs e)
    {
      this.Suppliers.AddRange(this.SelectedReceiverSuppliers);

      foreach (Leverancier supplier in this.SelectedReceiverSuppliers)
      {
        this.ReceiverSuppliers.Remove(supplier);
      }

      List<Leverancier> selectedReceiverSupplier = new List<Leverancier>();
      if (this.ReceiverSuppliers.Count > 0)
      {
        selectedReceiverSupplier.Add(this.ReceiverSuppliers.First());
      }

      this.RefreshGrids(this.SelectedReceiverSuppliers, selectedReceiverSupplier);
    }

    private void btnRemoveAllSuppliers2Receiver_Click(object sender, EventArgs e)
    {
      List<Leverancier> selectedSuppliers = this.ReceiverSuppliers;

      this.Suppliers.AddRange(this.ReceiverSuppliers);
      this.ReceiverSuppliers = new List<Leverancier>();

      this.RefreshGrids(selectedSuppliers, new List<Leverancier>());
    }

    private void btnSend_Click(object sender, EventArgs e)
    {
      if (this.Send())
      {
        if (MessageBox.Show("Email met de offerte aanvraag is verzonden naar de leverancier(s).", "Verzonden", MessageBoxButtons.OK, MessageBoxIcon.Information) == DialogResult.OK)
        {
          this.OnOfferRequestSend();

          this.Close();
        }
      }
      else
      {
        MessageBox.Show(String.Format("Er is iets misgegaan tijdens het verzenden van de email(s).{0}Neem contact op met uw beheerder.", Environment.NewLine), "Fout", MessageBoxButtons.OK, MessageBoxIcon.Error);
      }
    }
    #endregion
  }

  public class OfferRequestSendEventArgs : EventArgs
  {
    private OfferteAanvraag offerRequest;

    public OfferRequestSendEventArgs(OfferteAanvraag offerRequest)
    {
      this.offerRequest = offerRequest;
    }

    public OfferteAanvraag OfferRequest
    {
      get { return this.offerRequest; }
    }
  }
}
